package com.soft.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.soft.entity.Store;
import com.soft.entity.User;

import com.soft.mapper.StoreMapper;
import com.soft.mapper.UserMapper;

@Service
public class UserService {
	@Autowired
	private UserMapper userMapper;

	public List<User> queryAll(){
		List<User> userList = userMapper.selectList(null);
		return userList;
	}
	

	public Long getUserIdByEmail(String userEmail) {
        // 1. 创建查询条件构造器
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        // 2. 添加条件：手机号精确匹配
        queryWrapper.eq("user_email", userEmail);
        // 3. 只查询需要的字段（优化性能，可选）
        queryWrapper.select("user_id"); // 只查询user_id字段
        
        // 4. 执行查询，获取用户对象
        User user = userMapper.selectOne(queryWrapper);
        
        // 5. 若用户存在则返回userId，否则返回null
        return user != null ? user.getUserId() : null;
    }
	
	// 登录（邮箱或手机号 + 密码）
	public User login(String account, String userPassword) {
	    QueryWrapper<User> qw = new QueryWrapper<>();
	    qw.eq("user_password", userPassword)
	      .and(wrapper -> wrapper.eq("user_email", account).or().eq("user_phone", account));
	    return userMapper.selectOne(qw);
	}


    // 注册
    public User register(String userEmail, String userPhone, String userPassword) {
        // 检查邮箱是否存在
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_email", userEmail);
        User existing = userMapper.selectOne(qw);
        if (existing != null) return null;

        User newUser = new User();
        newUser.setUserEmail(userEmail);
        newUser.setUserPhone(userPhone);
        newUser.setUserPassword(userPassword);
        int result = userMapper.insert(newUser);
        return result > 0 ? newUser : null;
    }

    // 忘记密码（更新密码）
    public boolean resetPassword(String userEmail, String newPassword) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("user_email", userEmail);
        User user = userMapper.selectOne(qw);
        if (user == null) return false;
        user.setUserPassword(newPassword);
        return userMapper.updateById(user) > 0;
    }

	
	
}